//
//  EmoticonViewController.swift
//  表情键盘
//
//  Created by mac on 15/9/17.
//  Copyright © 2015年 itcast. All rights reserved.
//

import UIKit

private let EmoticonCellID = "EmoticonCellID"
class EmoticonViewController: UIViewController {
    /// 选中表情的回调闭包
    var selectedEmoticonCallBack: (emoticon:Emoticon) ->()
    
    init(selectedEmoticon: (emoticon:Emoticon) ->()){
        selectedEmoticonCallBack = selectedEmoticon
        
        super.init(nibName:nil,bundle:nil)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    @objc private func clickItem(item: UIBarButtonItem)
    {
        let indexPath = NSIndexPath(forRow: 0, inSection: item.tag)
        
        //让collectionView 滚到对应的位置的左边
        collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: UICollectionViewScrollPosition.Left, animated: true)
        
        print(item.tag)
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.blueColor()
       
//        //TODO:加载表情数据
//        viewModel.loadPackages()
        setupUI()
    }
   
    private func setupUI(){
        ///1,添加控件
        view.addSubview(collectionView)
        view.addSubview(toolBar)
        
        /// 2，自动布局
        collectionView.translatesAutoresizingMaskIntoConstraints = false
        toolBar.translatesAutoresizingMaskIntoConstraints = false
        
        let viewDict = ["tb": toolBar, "cv": collectionView]
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[cv]-0-|", options: [], metrics: nil, views: viewDict))
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[tb]-0-|", options: [], metrics: nil, views: viewDict))
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[cv]-[tb(44)]-0-|", options: [], metrics: nil, views: viewDict))
        
        prepareToolbar()
        prepareCollectionView()
    }
    ///准备toolBar控件
    private func prepareToolbar(){
        toolBar.tintColor = UIColor.darkGrayColor()
        
        var items = [UIBarButtonItem]()
        // 通常用 tag 来区别 toolbar 上的按钮，一组相近，而且是顺序的操作
        var index = 0
        
        for title in ["最近", "默认", "emoji", "浪小花"]{
            items.append(UIBarButtonItem(title: title, style: UIBarButtonItemStyle.Plain, target: self, action: "clickItem:"))
            items.last?.tag = index++
            
            items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
        }
        items.removeLast()
        
        toolBar.items = items
        
    }
    /// 注册可重用cell
    private func prepareCollectionView(){
      
        collectionView.registerClass(EmotionCell.self, forCellWithReuseIdentifier: EmoticonCellID)
       
        collectionView.backgroundColor = UIColor.whiteColor()
        //指定数据源
        collectionView.dataSource = self
        //指定代理方法
        collectionView.delegate = self
    
    }

    private lazy var toolBar = UIToolbar()
    private lazy var collectionView = UICollectionView (frame: CGRectZero, collectionViewLayout: EmoticonLayout())
  //  private lazy var viewModel = EmoticonViewModel()
    private lazy var viewModel = EmoticonViewModel.shareViewModel
    
}

/// 表情键盘自动布局
private class EmoticonLayout: UICollectionViewFlowLayout{
    /// 准备布局，第一次使用的时候会被调用 － collectionView 的大小已经确定(已经完成自动布局)
    /// 准备布局方法，会在数据源(cell 的个数)前调用，可以在此准备 layout 的属性
    private override func prepareLayout() {
        super.prepareLayout()
        let w = collectionView!.bounds.width / 7
        // iPhone 5 如果用 0.5 会每页显示两行，因为浮点数的原因，计算会有偏差！
        let margin = (collectionView!.bounds.height - 3 * w) * 0.499
        
        itemSize = CGSize(width: w, height:w)
        minimumInteritemSpacing = 0
        minimumLineSpacing = 0
        
        sectionInset = UIEdgeInsets(top: margin, left: 0, bottom: margin, right: 0)
        
        scrollDirection = UICollectionViewScrollDirection.Horizontal
        collectionView?.pagingEnabled = true
        collectionView?.showsHorizontalScrollIndicator = false
    }
}

extension EmoticonViewController:UICollectionViewDataSource,UICollectionViewDelegate
{
    //分组数量
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return viewModel.packages.count
    }
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return viewModel.packages[section].emoticons.count
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(EmoticonCellID, forIndexPath: indexPath) as! EmotionCell
        //cell.backgroundColor = (indexPath.item) % 2 == 0 ? UIColor.blueColor(): UIColor.redColor()
        //设置表情索引
        
        cell.emoticon = viewModel.emoticon(indexPath)
        return cell
    }
    
    //选中cell的代理方法
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
    //执行回调闭包
        selectedEmoticonCallBack(emoticon: viewModel.emoticon(indexPath))
        
        viewModel.favorite(indexPath)
        // 刷新 collectionView 第0组
        // 用户体验不好：会闪动/表情会变化位置
        // collectionView.reloadSections(NSIndexSet(index: 0))
    }
}
private class EmotionCell: UICollectionViewCell{
  
    //表情模型
    var emoticon: Emoticon?{
        didSet{
            // 以下两个清空的动作，能够解决重用的问题
            // 1. 图片 - 如果没有会清空图片
            emotionButton.setImage(UIImage(contentsOfFile: emoticon!.imagePath), forState: UIControlState.Normal)
            /// 2,emoji - 如果没有会清空文字
            emotionButton.setTitle(emoticon!.emoji, forState: UIControlState.Normal)
            
            /// 3,删除按钮
            if emoticon!.isRemove {
                emotionButton.setImage(UIImage(named: "compose_emotion_delete"), forState: UIControlState.Normal)
                emotionButton.setImage(UIImage(named: "compose_emotion_delete_highlighted"), forState: UIControlState.Highlighted)
            }
        }
    }
    
    override init(frame: CGRect){
        super.init(frame: frame)
        contentView.addSubview(emotionButton)
        emotionButton.backgroundColor = UIColor.whiteColor()
        //CGRectInset返回相同中心的矩形
        //一定要用bounds
        emotionButton.frame = CGRectInset(bounds, 4, 4)
        
        emotionButton.titleLabel?.font = UIFont.systemFontOfSize(32)
        //禁用按钮
        emotionButton.userInteractionEnabled = false
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private lazy var emotionButton: UIButton = UIButton()
}